<template>
  <template v-if="cfg.mobile == false">
    <div :class="`header_box_top bdw `">
      <div :class="`header_box1_top`">
        <n-tabs
          :bar-width="0"
          class="guild_tab"
          justify-content="center"
          type="line"
          :value="cfg.route.name"
          animated
        >
          <template v-for="item in cfg.lv2tab">
            <n-tab-pane v-if="ct.qxpd(item) == true" :name="item.name" :tab="item.title">
              <template #tab>
                <router-link
                  :to="{
                    name: item.name,
                    params: item.params ?? [],
                  }"
                >
                  <div class="_div">
                    <n-icon size="30" :component="item?.icon" />
                    {{ item.title }}
                  </div>
                </router-link></template
              >
            </n-tab-pane>
          </template>
        </n-tabs>
      </div>
      <div :class="`header_box2_top`">
        <router-link
          :to="{
            name: `home`,
            params: {
              id: `info`,
            },
          }"
        >
          <div v-if="cfg.user?.uid != null" class="header_item header_item_top">
            <n-icon size="25" :component="UserOutlined" />

            <div>个人</div>
          </div>
        </router-link>
        <div :class="`header_item header_item_top`">
          <n-icon
            @click="cfg.loginif = true"
            v-if="cfg.user?.uid == null"
            size="25"
            :component="QqCircleFilled"
          />
          <n-icon
            @click="cfg.loginout()"
            v-if="cfg.user?.uid != null"
            size="25"
            :component="CloseSquareOutlined"
          />
          <span v-if="cfg.user?.uid == null" @click="cfg.loginif = true">登录</span>
          <div @click="cfg.loginout()" v-if="cfg.user?.uid != null">登出</div>
        </div>
      </div>
    </div>
  </template>
  <template v-else> </template>
  <component :is="comp.pc_login" :val="val" :ct="ct" />
</template>
<style scoped>
.header_item {
  display: flex;
  cursor: pointer;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.header_item:hover {
  color: #757575;
}

.header_item_r_left {
  margin-bottom: 12px;
}

.header_item_active {
  color: #757575;
  font-weight: bold;
  font-size: 14px;
}
.header_box_left {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  gap: 12px;
  color: #61666d;
}
.header_box_top {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 12px;
  color: #61666d;
  position: relative;
  padding-top: 8px;
  align-items: center;
}
._header_top {
  margin-bottom: 5px;
}
.header_box1_left {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.header_box1_top {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 25px;
  justify-content: center;
}

.header_box2_left {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.header_box2_top {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 12px;
  justify-content: center;
  position: absolute;
  right: 6px;
  top: 11px;
}
</style>

<script>
import { Menu } from "@element-plus/icons";
import {
  AlertOutlined,
  FundOutlined,
  CrownOutlined,
  PieChartOutlined,
  TeamOutlined,
  ToolOutlined,
} from "@vicons/antd";
import {
  NodeIndexOutlined,
  AppstoreOutlined,
  SyncOutlined,
  CloseSquareOutlined,
  QqCircleFilled,
  AndroidOutlined,
  SettingOutlined,
  UserOutlined,
} from "@vicons/antd";

import axios from "axios";
import { cfg } from "@/cfg/cfg.js";
import { useNotification } from "naive-ui";
import { getuser } from "@/cfg/function.js";
import { v4 as uuidv4 } from "uuid";

export default defineComponent({
  components: {
    Menu,
  },
  setup() {
    const notification = useNotification();
    const message = useMessage();
    const Dialog = useDialog();
    cfg.nf = notification;
    cfg.msg = message;
    cfg.alert = Dialog;
    //中文测试
    cfg.消息 = cfg.msg;
    cfg.输出 = console.log;
    cfg.报错 = console.error;
    cfg.真 = true;
    cfg.假 = false;
    cfg.axios = axios;
    const comp = {
      AlertOutlined,
      FundOutlined,
      CrownOutlined,
      PieChartOutlined,
      TeamOutlined,
      ToolOutlined,
      pc_login: defineAsyncComponent(() => import("./all/login.vue")),
    };
    let val = reactive({
      back: {},
      tabck: null,
      timer: null,
      maxth: 200,
    });

    let ct = {
      qxpd: (item) => {
        const user = cfg.user;

        if (item.mobile == true) {
          if (cfg.mobile == true) {
            return true;
          } else {
            return false;
          }
        }
        if (user?.group?.admin == true) {
          return true;
        }
        if (item.bz == true) {
          if (user?.group?.Introduction == true) {
            return true;
          } else {
            return false;
          }
        }
        if (item.login == true) {
          if (user?.uid?.length >= 1) {
            return true;
          } else {
            return false;
          }
        }
        return true;
      },
      login_p2: async (rdid) => {
        try {
          let res = await cfg.axios.get(`${cfg.url}`, {
            params: {
              t: "v2/get",
              t2: "os/qqend",
              authkey: cfg.user?.authkey,
              uid: cfg.user?.uid,
              uuid: rdid,
            },
          });
          if (res.data.code == 0) {
            if (res.data.msg == "老用户登录") {
              cfg.token = res.data.data.token;
              localStorage.setItem("token", cfg.token);
              getuser();
              cfg.loginif = false;
              cfg.msg.success("登录成功");
              return;
            }
            if (res.data.msg == "新用户选择") {
              cfg.alert.warning({
                title: "登录提示",
                content:
                  "当前QQ账号未绑定猫燐工具箱账号，请登录后绑定账号，或一键注册猫燐工具箱新账号。",
                positiveText: "一键注册",
                negativeText: "登录后绑定",
                draggable: true,
                onPositiveClick: async () => {
                  let res = await cfg.axios.get(`${cfg.url}`, {
                    params: {
                      t: "v2/get",
                      t2: "os/qqend",
                      t3: "reg",
                      uuid: rdid,
                    },
                  });
                  if (res.data.code == 0) {
                    cfg.token = res.data.data.token;
                    localStorage.setItem("token", cfg.token);
                    getuser();
                    cfg.loginif = false;
                    cfg.msg.success("注册登录成功");
                    return;
                  } else {
                    cfg.msg.error(res.data.msg);
                  }
                },
                onNegativeClick: async () => {
                  cfg.loginif = true;
                  cfg.opid_loginbind = true;
                  cfg.opid_uuid = rdid;
                },
              });
              return;
            }
          } else {
            cfg.msg.error(res.data.msg);
          }
        } catch (error) {
          alert(error);
        }
      },
      login: () => {
        //生成一个uuid
        const rdid = uuidv4();
        if (cfg.jsb == true) {
          localStorage.setItem("login_uuid", rdid);
          localStorage.setItem("login_stat", "yes");
          //获取当前域名
          const fullUrl = `${window.location.protocol}//${window.location.host}/`;
          const url = encodeURIComponent(fullUrl);
          const A = window.open(
            `https://sv2api.ww2.ren/?t=get/os/qqauth&xapp-target=browser&uuid=${rdid}&rf=${url}`
          );
          clearInterval(val.qqtimer);
          val.qqtimer = setInterval(async () => {
            if (A.closed) {
              //重载页面
              location.reload(true);
              return;
            }
          }, 1000);
        } else {
          if (cfg.mobile == true) {
            //跳转网站
            window.location.replace(
              `https://sv2api.ww2.ren/?t=get/os/qqauth&uuid=${rdid}`
            );
          } else {
            var A = window.open(
              `https://sv2api.ww2.ren/?t=get/os/qqauth&uuid=${rdid}`,
              "TencentLogin",
              "width=450,height=320,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1"
            );
            //检查是否被关闭
            clearInterval(val.qqtimer);
            val.qqtimer = setInterval(async () => {
              if (A.closed) {
                clearInterval(val.qqtimer);
                await ct.login_p2(rdid);
                return;
              }
            }, 1000);
          }
        }
      },
      downqr: () => {
        const canvas = document.querySelector("#qr-code")?.querySelector("canvas");
        if (canvas) {
          const url = canvas.toDataURL();
          const a = document.createElement("a");
          a.download = "QRCode.png";
          a.href = url;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }
      },
      tab: (tab) => {
        val.tabck = tab;
        clearInterval(val.timer);
      },
      axioslogin: () => {
        let newmsg = cfg.msg.loading("请求服务器中...");
        const config2 = {
          method: "post",
          url: `${cfg.url}?t=post/user/login`, // 目标URL
          data: cfg.loginfm,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };

        axios(config2)
          .then(async function (response) {
            val.back = response?.data;
            newmsg.destroy();
            if (response?.data?.code == -1) {
              cfg.alert3({
                title: "登录失败",
                message: response?.data?.msg,
                closeOnClickOverlay: true,
              });
              return;
            }
            if (response?.data?.code == 0) {
              cfg.msg.success(`登录成功`);
              cfg.loginif = false;
              cfg.token = response.data.data.token;
              localStorage.setItem("token", cfg.token);
              getuser();
              return;
            }
            return;
          })
          .catch(function (error) {
            alert(error);
          });
      },
      axiosregister: () => {
        let newmsg = cfg.msg.loading("请求服务器中...");
        const config2 = {
          method: "post",
          url: `${cfg.url}?t=post/user/register`, // 目标URL
          data: cfg.loginfm,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };

        axios(config2)
          .then(async function (response) {
            val.back = response?.data;
            newmsg.destroy();
            if (response?.data?.code == -1) {
              cfg.alert3({
                title: "注册失败",
                message: response?.data?.msg,
                closeOnClickOverlay: true,
              });
              return;
            }
            if (response?.data?.code == 0) {
              cfg.msg.success(`注册成功`);
              cfg.loginif = false;
              cfg.token = response.data.token;
              localStorage.setItem("token", cfg.token);
              getuser();
              return;
            }
            return;
          })
          .catch(function (error) {
            alert(error);
          });
      },
    };

    cfg.hdct = ct;

    onMounted(async () => {
      if (cfg.login_stat == "yes") {
        const uuid = cfg.login_uuid;
        await ct.login_p2(uuid);
        localStorage.removeItem("login_uuid");
        localStorage.removeItem("login_stat");
      }

      if (cfg.route?.query?.login == "qq") {
        const rdid = cfg.route.query.uuid;
        const ymid = cfg.route.query.ymapp;
        //去掉route的uuid
        cfg.router.replace({
          query: {
            ...cfg.route.query,
            uuid: null,
            ymid: null,
            login: null,
          },
        });

        if (ymid == "yes") {
          alert("现在关闭浏览器，返回APP即可完成QQ登录。");
        }
        await ct.login_p2(rdid);
      }
    });

    return {
      val,
      ct,
      QqCircleFilled,
      cfg,
      SyncOutlined,
      notification,
      AppstoreOutlined,
      message,
      AndroidOutlined,
      CloseSquareOutlined,
      UserOutlined,
      NodeIndexOutlined,
      SettingOutlined,
      comp,
    };
  },
  watch: {
    "cfg.loginif": {
      handler(newVal) {
        if (newVal == false) {
          clearInterval(this.val.timer);
        }
      },
      immediate: true,
    },
  },
});
</script>
